package com.qiwo.common.controller;

import com.qiwo.common.utils.UploadProperties;
import io.swagger.annotations.ResponseHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.util.Base64;

/**
 * Copyright
 *
 * @Author:chenwenchao
 * @Date:2018/9/27 0027
 * Description:
 */
@Controller
public class HomeController {

    private final ResourceLoader resourceLoader;

    @Resource
    private UploadProperties uploadProperties;
    @Autowired
    public HomeController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    @RequestMapping(method = RequestMethod.GET, value = "/uploadImg/{filename:.+}")
    @ResponseBody
    public void getFile(@PathVariable String filename, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String Type=filename.substring(filename.lastIndexOf("."));
        filename= filename.substring(0,filename.lastIndexOf("."));
        String realPath=new String(Base64.getDecoder().decode(filename), "UTF-8")+Type;
        try {
       org.springframework.core.io.Resource object= resourceLoader.getResource("file:" + Paths.get(uploadProperties.getBasePath(),realPath));
            if(object.isFile()) {
                File file=object.getFile();
                if (file.isFile()) {
                    //读图片
                    FileInputStream inputStream = new FileInputStream(file);
                    int available = inputStream.available();
                    byte[] data = new byte[available];
                    inputStream.read(data);
                    inputStream.close();
                    //写图片
                    response.setContentType("image/" + Type.replace(".", ""));
                    response.setCharacterEncoding("UTF-8");
                    OutputStream stream = new BufferedOutputStream(response.getOutputStream());
                    stream.write(data);
                    stream.flush();
                    stream.close();
                }
            }
           // return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(uploadProperties.getBasePath(),realPath)));
        } catch (Exception e) {
            e.printStackTrace();
           // return ResponseEntity.notFound().build();
        }
    }
}
